<?php

namespace Admin\Forms;

/**
 * Description of Product
 *
 * @author nofear
 */
class Product {
    
    private $view;
    private $Object;
    private $methods;
    private $annotations = array(
        'mark' => '\Shared\Main\Metadata'
    );
    
    public function __construct($Object = null) {
        $this->Object = $Object ? : new \Shared\Main\Domain;
        $this->methods = $this->getMethods($this->Object);
        $this->EntityManager = \Shared\Application::getInstance()->getEntityManager();
        
        $this->view = new \System\Template('@forms/product.twig');
    }
    
    public function render() {
        foreach ( $this->methods as $method => $value ) {
            $this->view->$method = $value;
        }
        
        $this->view->categories = $this->EntityManager->getRepository('Shared\Main\Category')->findAll();
        
        $this->view->Object = $this->Object;
        $this->view->metaDescription = $this->Object->getMetadata() ? $this->Object->getMetadata()->getDescription() : '';
        $selectedData = array();
        
        if ($this->Object->getMetadata() && $this->Object->getMetadata()->getTags() && count($this->Object->getMetadata()->getTags()))
            foreach ($this->Object->getMetadata()->getTags() as $Tag) {
                $selectedData[] = array('value' => $Tag->getName(), 'id' => $Tag->getId());
        }
        
        $this->view->selectedData = json_encode($selectedData);
        
        if ( $this->Object->getId() ) {
            $this->view->pictures = $this->EntityManager->getRepository('Shared\Main\SiteObject')->getAllPictures($this->Object, $force = true);
        }
        
        return $this->view->paste();
    }
    
    private function getMethods($Object) {
        $methods = get_class_methods($Object);
        $tmp = array();

        foreach ($methods as $method) {
            if (substr($method, 0, 3) == 'get') {
                if (is_object($Object->{$method}()) || isset($this->annotations[strtolower(substr($method, 3))])) {
                    if ( is_object($Object->{$method}()) ) {
                        $tmp[lcfirst(substr($method, 3))] = $Object->{$method}();
                    } else {
                        $tmp[lcfirst(substr($method, 3))] = new $this->annotations[strtolower(substr($method, 3))];
                    }
                } else {
                    $tmp[lcfirst(substr($method, 3))] = $Object->{$method}();
                }
            }
        }

        return $tmp;
    }
}
